iT邦幫忙

2021 iThome 鐵人賽

DAY 5
0

今天我們要介紹的是python的串列,所謂的串列就是指將元素用[]包住並且是有順序性的資料型態。

串列(List)

以下我們介紹幾個間單的串列型態以及如果對串列做變化。

data = ["apple","banana","watermelon","orange","grape"]
print(data)

首先我們先宣告一個串列的變數。

data = ["apple","banana","watermelon","orange","grape"]
for i in data:
    print(i)

也可以用昨天所學到的利用FOR迴圈來抓取列表裡面的每一個元素。

data = ["apple","banana","watermelon","orange","grape"]
for i in data:
    if i == "orange":
        print(i)

如果知道串列的內容,也可以用特定的條件去抓取想要的資料。

data = ["apple","banana","watermelon","orange","grape"]
data1 = ["good","bad","good","good","bad"]
data2 = [50,60,73,81,39]
print(data[0])
print(data1[2])
print(data2[4])

如果知道串列內容以及位址的話也可以直接抓取而不需要用條件抓取,而串列的順序是從0開始。

data = ["apple","banana","watermelon","orange","grape"]
data1 = ["good","bad","good","good","bad"]
data2 = [50,60,73,81,39]
print(data[0:3])
print(data1[2:4])
print(data2[4])

串列也可以抓取不只單一一個的元素,也可以抓取多個或範圍的元素,可以使用[n:n-1]的範圍抓取。

data = ["apple","banana","watermelon","orange","grape"]
data1 = ["good","bad","good","good","bad"]
data2 = [50,60,73,81,39]
print(data)
print(data1)
print(data2)
data.append("mango")
data1.append("good")
data2.append(90)
print(data)
print(data1)
print(data2)

也可以對串列做增加的動作,利用.apppend的方式將想要的資料增加進串列裡面。

data = ["apple","banana","watermelon","orange","grape"]
data1 = ["good","bad","good","good","bad"]
data2 = [50,60,73,81,39]
print(data)
print(data1)
print(data2)
data.remove("apple")
data1.remove("bad")
data2.remove(39)
print(data)
print(data1)
print(data2)

也可以對串列做刪除的動作,利用.remove的方式將想要的資料做刪除,如果資料內有相同元素的資料,將會以順序最前面的開始做刪除。

以上就是簡單的python串列的介紹,明天我們將介紹python的集合。


上一篇
Day 4 python迴圈
下一篇
Day 6 python集合
系列文
新手也想開始認識機器學習30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言